package org.hbbTlias2025.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtil {

    private static final String SECRET_KEY = "aGJi";
    private static final long EXPIRATION_TIME = 12 * 60 * 60 * 1000; // 12 hours

    /**
     * Generate a JWT token.
     * @param id The ID to be stored in the token.
     * @param username The username to be stored in the token.
     * @return The generated JWT token.
     */
    public static String generateToken(Map<String, Object> claims) {
        String token = Jwts.builder()
                .setSubject((String) claims.get("username")) // Assuming username is used as subject
                .addClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();

        log.info("JWT生成成功---" + token);
        return token;
    }

    /**
     * Parse a JWT token and retrieve its claims.
     * @param token The JWT token to be parsed.
     * @return Claims containing the payload of the token.
     */
    public static Claims parseToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();

        log.info("JWT解析成功---" + claims);
        return claims;
    }
}